package com.wuwei.elearning.question.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuwei.elearning.dto.ConversionMessage;
import com.wuwei.elearning.enumPackage.Constant;
import com.wuwei.elearning.exception.ElearningMysqlException;
import com.wuwei.elearning.messageQueen.Message;
import com.wuwei.elearning.messageQueen.MessageQueue;
import com.wuwei.elearning.question.domain.Subject;
import com.wuwei.elearning.question.domain.Word;
import com.wuwei.elearning.question.mapper.SubjectMapper;
import com.wuwei.elearning.question.mapper.WordMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuwei.elearning.question.service.WordService;
import com.wuwei.elearning.service.CacheService;
import com.wuwei.elearning.utils.MinioUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuwei
 * @since 2025-03-20
 */
@Service
@Slf4j
public class WordServiceImpl extends ServiceImpl<WordMapper, Word> implements WordService {

    @Resource
    private MinioUtil minioUtil;

    @Resource
    private WordMapper wordMapper;

    @SneakyThrows
    @Override
    @Transactional
    public void insert(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        LambdaQueryWrapper<Word> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Word::getName,originalFilename);
        Word Word = wordMapper.selectOne(queryWrapper);
        if (Word!=null) {
            throw new ElearningMysqlException(30011,"上传失败！该文件已存在！");
        }else {
            Word word = new Word();
            word.setName(originalFilename);
            wordMapper.insert(word);
            // 1. 先将文件上传到MinIO
            String tempPath = "temp/" + originalFilename;
            minioUtil.uploadToPath(file,tempPath);
            // 2. 只发送元数据到Kafka
            Message message = new Message();
            message.setFileName(originalFilename);
            message.setId(word.getId());
            message.setMinioPath(tempPath); // 存储MinIO中的路径，而不是文件内容
            messageQueue.send(Constant.WORD_CONVERSION_TOPIC, message,message.getId());
        }
    }


    @Autowired
    private MessageQueue messageQueue;


    @Resource
    private CacheService cacheService;

    @Override
    @Transactional
    public void delete(Word word) {
        log.info("即将删除的word-{}",word.getName());
        Word selectById = wordMapper.selectById(word.getId());
        String objectName = selectById.getUrl();
        minioUtil.remove(objectName);
        String url = wordMapper.selectById(word.getId()).getUrl();
        // 构建Redis键
        String redisKey = Constant.MINIO_PDF + url;
        cacheService.delete(redisKey);
        wordMapper.deleteById(word.getId());
        List<Subject> subjects = subjectMapper.findAllLeafs();
        for (Subject subject : subjects) {
            String words = subject.getWords();
            if (words!=null) {
                List<Long> wordList = JSON.parseArray(words, Long.class).stream().filter(id->!id.equals(word.getId())).collect(Collectors.toList());
                subject.setWords(JSON.toJSONString(wordList));
                subjectMapper.updateById(subject);
            }
        }
    }

    @Resource
    private SubjectMapper subjectMapper;

}
